package com.yangtu.nearbyshop.admin.web;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangtu.nearbyshop.admin.annotation.RequiresPermissionsDesc;
import com.yangtu.nearbyshop.admin.util.AdminResponseCode;
import com.yangtu.nearbyshop.core.util.JacksonUtil;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.core.validator.Sort;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopMercRebateService;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopMercRebateSettleService;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopOrderRefundService;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopOrderService;
import com.yangtu.nearbyshop.db.util.OrderHandleOption;
import com.yangtu.nearbyshop.db.util.OrderUtil;
import com.yangtu.nearbyshop.db.vo.OrderRefundVo;
import com.yangtu.nearbyshop.db.vo.SaleCountVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.yangtu.nearbyshop.admin.service.AdminOrderService;
import com.yangtu.nearbyshop.core.validator.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/order")
@Validated
public class AdminOrderController {
    private final Log logger = LogFactory.getLog(AdminOrderController.class);

    /**
     * @apiDefine order 订单相关接口
     *
     */

    @Autowired
    private AdminOrderService adminOrderService;

    @Autowired
    private INearbyshopOrderRefundService refundService;

    @Autowired
    private INearbyshopOrderService orderService;

    @Autowired
    private INearbyshopMercRebateService rebateService;

    @Autowired
    private INearbyshopMercRebateSettleService rebateSettleService;

    @Value("${nearbyshop.orgNative}")
    private String orgNative;

    /**
     * 查询订单
     *
     * @param userId
     * @param orderSn
     * @param orderStatusArray
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:order:list")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(Integer userId, String orderSn,String startTm,String endTm,
                       String consignee,String mobile,String mercName,
                       @RequestParam(required = false) List<Short> orderStatusArray,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        return adminOrderService.list(userId, orderSn, orderStatusArray, page, limit, sort, order,startTm,endTm,
                consignee,mobile,mercName);
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:order:read")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单管理"}, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        return adminOrderService.detail(id);
    }

    /**
     * 订单退款
     *
     * @param body 订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    @RequiresPermissions("admin:order:refund")
    @RequiresPermissionsDesc(menu = {"订单管理", "退款管理"}, button = "订单退款")
    @PostMapping("/refund")
    public Object refund(@RequestBody String body) {
        //if(orgNative.equals("yes")){
            return adminOrderService.refundNative(body);
        //}
        //return adminOrderService.refund(body);
//        return adminOrderService.refundNative(body);
    }

    /**
     * 订单退款
     *
     * @param body 订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    @RequiresPermissions("admin:order:unrefund")
    @RequiresPermissionsDesc(menu = {"订单管理", "退款管理"}, button = "取消退款")
    @PostMapping("/unrefund")
    public Object unrefund(@RequestBody String body) {
        return adminOrderService.unrefund(body);
    }

    /**
     * 发货
     *
     * @param body 订单信息，{ orderId：xxx, shipSn: xxx, shipChannel: xxx }
     * @return 订单操作结果
     */
    @RequiresPermissions("admin:order:ship")
    @RequiresPermissionsDesc(menu = {"订单管理", "发货管理"}, button = "订单发货")
    @PostMapping("/ship")
    public Object ship(@RequestBody String body) {
        return adminOrderService.ship(body);
    }


    /**
     * 回复订单商品
     *
     * @param body 订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    @RequiresPermissions("admin:order:reply")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单管理"}, button = "订单商品回复")
    @PostMapping("/reply")
    public Object reply(@RequestBody String body) {
        return adminOrderService.reply(body);
    }


    /**
     * @api {POST} /admin/order/refundApply 添加人工退款
     * @apiName order refundApply
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} orderSn 订单编号
     * @apiParam {String} [refundReason] 退款原因
     * @apiParam {double} refundPrice 退款金额
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:order:refundApply")
    @RequiresPermissionsDesc(menu = {"订单管理", "退款管理"}, button = "记录退款")
    @PostMapping("/refundApply")
    public Object refundApply(@RequestBody NearbyshopOrderRefund body) {
        if (body==null || body.getOrderSn() == null || body.getRefundPrice() == null) {
            return ResponseUtil.badArgument();
        }

        NearbyshopOrder2 order = orderService.getOne(new QueryWrapper<NearbyshopOrder2>()
            .eq("order_sn",body.getOrderSn())
            .eq("deleted",0));
        if(order == null){
            return ResponseUtil.fail("订单不存在");
        }
        NearbyshopOrder od = new NearbyshopOrder();
        od.setId(order.getId());
        od.setOrderStatus(order.getOrderStatus().shortValue());
        OrderHandleOption handleOption = OrderUtil.build(od);
        if (!handleOption.isRgrefund()) {
            return ResponseUtil.fail(AdminResponseCode.ORDER_CANT_REFUND, "订单不能退款");
        }
        body.setOrderId(order.getId());
        refundService.refundApply(body);
        adminOrderService.refund("{\"orderId\":\""+body.getOrderId()+"\",\"refundPrice\":"+body.getRefundPrice()+"}");
        return ResponseUtil.ok();
    }

    /**
     * @api {GET} /admin/order/refundList 退款列表
     * @apiName order refundList
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} refundBy 退款途径   1：自动   2：手动
     * @apiParam {int} userId 用户id
     * @apiParam {int} orderStatus 订单状态
     * @apiParam {int} orderId 订单id
     * @apiParam {String} [startTm] 退款时间开始
     * @apiParam {String} [endTm] 退款时间结束
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:order:refundList")
    @RequiresPermissionsDesc(menu = {"订单管理", "退款管理"}, button = "退款列表")
    @GetMapping("/refundList")
    public Object refundList(String startTm,String endTm,String refundBy,
                             Integer userId,Integer orderStatus,Integer orderId,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer limit) {
        Page<NearbyshopOrderRefund> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopOrderRefund> pList = refundService.page(pageVo,new QueryWrapper<NearbyshopOrderRefund>()
                .eq(userId != null ,"user_id",userId)
                .eq(orderStatus != null ,"order_status",orderStatus)
                .eq(orderId != null ,"order_id",orderId)
                .eq(refundBy != null ,"refund_by",refundBy)
                .ge(!StringUtils.isEmpty(startTm),"handle_time",startTm)
                .le(!StringUtils.isEmpty(endTm),"handle_time",endTm)
                .orderByDesc("handle_time"));
        OrderRefundVo refundVo = refundService.countRefund(userId,orderStatus,orderId,refundBy,startTm,endTm);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        data.put("settle", refundVo);
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/order/refundDetail 退款列表
     * @apiName order refundDetail
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} refundBy 退款途径   1：自动   2：手动
     * @apiParam {int} userId 用户id
     * @apiParam {int} orderStatus 订单状态
     * @apiParam {int} orderId 订单id
     * @apiParam {String} [startTm] 退款时间开始
     * @apiParam {String} [endTm] 退款时间结束
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:order:refundDetail")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单管理"}, button = "退款详情")
    @GetMapping("/refundDetail")
    public Object refundDetail(@NotNull Integer id) {
        return refundService.getById(id);
    }


    /**
     * @api {GET} /admin/order/saleCountAll 销售总额统计
     * @apiName order saleCountAll
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} startTm 退款时间开始
     * @apiParam {String} endTm 退款时间结束
     * @apiParam {int} page 页码
     * @apiParam {int} limit 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:order:saleCountAll")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单统计"}, button = "销售总额统计")
    @GetMapping("/saleCountAll")
    public Object refundList(String startTm,String endTm,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer limit) {
        //orderStatus 订单状态 （201：已支付  210：已采购  301：已发货  302：已提货  401+402：已收货）
        Page<SaleCountVo> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<SaleCountVo>  pList = orderService.sumAllSale(pageVo,startTm,endTm);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/order/saleCountGoods 商品销售统计
     * @apiName order saleCountGoods
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} startTm 退款时间开始
     * @apiParam {String} endTm 退款时间结束
     * @apiParam {String} goodsSn 商品sn
     * @apiParam {int} page 页码
     * @apiParam {int} limit 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:order:saleCountGoods")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单统计"}, button = "商品销售统计")
    @GetMapping("/saleCountGoods")
    public Object saleCountGoods(String startTm,String endTm,String goodsSn,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer limit) {
        //orderStatus 订单状态 （201：已支付  210：已采购  301：已发货  302：已提货  401+402：已收货）
        Page<SaleCountVo> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<SaleCountVo>  pList = orderService.sumAllSaleByGoods(pageVo,startTm,endTm,goodsSn);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/order/saleCountMerc 门店销售统计
     * @apiName order saleCountMerc
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} startTm 退款时间开始
     * @apiParam {String} endTm 退款时间结束
     * @apiParam {String} mercNo 门店编号
     * @apiParam {int} page 页码
     * @apiParam {int} limit 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:order:saleCountMerc")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单统计"}, button = "门店销售统计")
    @GetMapping("/saleCountMerc")
    public Object saleCountMerc(String startTm,String endTm,String mercNo,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer limit) {
        //orderStatus 订单状态 （201：已支付  210：已采购  301：已发货  302：已提货  401+402：已收货）
        Page<SaleCountVo> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<SaleCountVo>  pList = orderService.sumAllSaleByMerc(pageVo,startTm,endTm,mercNo);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/order/saleCountBD BD销售统计
     * @apiName order saleCountBD
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} startTm 退款时间开始
     * @apiParam {String} endTm 退款时间结束
     * @apiParam {String} bdNo BD编号
     * @apiParam {int} page 页码
     * @apiParam {int} limit 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:order:saleCountBD")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单统计"}, button = "BD销售统计")
    @GetMapping("/saleCountBD")
    public Object saleCountBD(String startTm,String endTm,String bdNo,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer limit) {
        //orderStatus 订单状态 （201：已支付  210：已采购  301：已发货  302：已提货  401+402：已收货）
        Page<SaleCountVo> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<SaleCountVo>  pList = orderService.sumAllSaleByBd(pageVo,startTm,endTm,bdNo);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }


    @RequiresPermissions("admin:order:mercSettle")
    @RequiresPermissionsDesc(menu = {"订单管理", "订单统计"}, button = "实时统计店铺返利")
    @GetMapping("/mercSettle")
    public Object mercSettle(String date) {
        logger.info("手动=系统开启任务=统计当天团长返利数据");
        if (StringUtils.isEmpty(date)) {
            return ResponseUtil.fail("缺少date");
        }
        String startTime = null;
        String endTime = null;
        if(!StringUtils.isEmpty(date)){
            startTime = date + " 00:00:00";
            endTime = date + " 23:59:59";
        }
        Page<NearbyshopMercRebate> pageVo = new Page<>();
        pageVo.setCurrent(1);
        pageVo.setSize(10000);
        IPage<NearbyshopMercRebateSettle> pList = rebateService.getDailyRebate(pageVo,
                null,null,startTime,endTime);
        for(NearbyshopMercRebateSettle rebate:pList.getRecords()){
            rebate.setAddTime(new Date());
        }
        rebateSettleService.saveBatch(pList.getRecords());
        logger.info("手动=结束：系统结束任务=统计当天团长返利数据。dataSize=" + pList.getRecords().size());
        return ResponseUtil.ok();
    }


}
